<?php

namespace app\index\controller;

use app\common\controller\Helptype;
use app\common\lib\YopClient3;
use app\common\lib\YopRequest;
use app\index\controller\Log\InsertLog;
use app\index\controller\Log\OperationLog;
use think\Config;
use think\Controller;
use think\Request;
use app\index\model\tan\Bankcard as b;
use app\index\controller\tan\ReturnData as js;
use app\index\controller\Sms\AliYunSms;
use app\index\model\tan\PhoneCode;
use think\Session;
use think\Db;
use think\Validate;

/**
 * 银行卡
 */
class Bankcard extends Controller
{

    /**
     * @var b
     */
    private static $Bankcard;
    public function __construct(b $Bankcard) {
        self::$Bankcard=$Bankcard;
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()    {
        //
        
        
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()    {
        //
    }

    /**
     * 添加银行卡
     * @param Request $request
     * @param PhoneCode $PhoneCode
     */
    public function save(Request $request,PhoneCode $PhoneCode)
    {

        $post =$request->post();
        tan\Ret::IfNoTrue( $this->validate($post, [
            "bankcard_id|银行卡"=>"require|alphaNum|max:20",
            "opening_bank|开会行"=>"require",
            //"opening_bank_address|开会行地址"=>"require",
            "code|验证码"=>"require|number",
            "phone|手机电话"=>"require|^1[0-9]{10}$",
            "name|开户人名称"=>"require|max:10",
        ]), 10006);
        $d=$PhoneCode->query([
            "phone"=>$post['phone'],
            "code"=>$post['code'],
            "user_id"=>Session::get("user.id")
        ]);
        tan\Ret::IfEmpty($d, 10004, "验证码错误");
        $bool=self::$Bankcard->save_($post);
        if($bool){
            js::ok();
        } else {
            js::err(10002,"未知");
        }
        
    }

    /**
     * 显示指定的银行卡
     *
     * @param  int  $id
     */
    public function read($id)
    {
        tan\Ret::IfEmptyExit(self::$Bankcard->query_($id) , 10003, "无数据或该银行卡无权限查看");
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 更新银行卡
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $post=$request->post();
        $rule=[
            "bankcard_id|银行卡"=>"require|alphaNum|max:20",
            "opening_bank|开会行"=>"require",
            "opening_bank_address|开会行地址"=>"max:10",
            "name|名称"=>"max:10",
            "phone|手机电话"=>"require|^1[0-9]{10}$",
            "default|是否设为默认银行卡"=>"in:0,1",
            "state|是否禁用"=>"in:0,1"
        ];
        tan\Ret::IfNoTrue( $this->validate($post, $rule), 10009);
        $data=tan\Eliminate::E($post, $rule);
        tan\Ret::Exit_(self::$Bankcard->up($id,$data), 10009,"无任何修改或无权修改");
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
    
    /**
     * 银行卡短信
     * @param \app\index\controller\AliYunSms $sms
     * @param \app\index\controller\PhoneCode $pc
     * @param type $mobile
     * @return json
     */
    public function sms(AliYunSms $sms, PhoneCode $pc,$mobile){
        $rund= rand(1000, 9999);
        $data= $sms ->code_type($rund,"reg")->setRecNum($mobile);
        if($data['code'] == 666){
            $pc->msg="reg";
            $pc->user_id =Session::get("user.id");
            $pc->createtime =date("Y-m-d H:i:s");
            $pc->code=$rund;
            $pc->phone=$mobile;
            $pc->save();
        }
       return $data;
    }

    /**
     * @return array
     * 获取银行列表
     */
    public function bank_list(){
        $back = ['code'=>666,'msg'=>'ok','data'=>[]];
        $bank_list =  Db::table('bank')
            ->where("state = 1")
            ->field(['id','name','code'])
            ->select();
        if(empty($bank_list)){
            $back['code'] = -1;
            $back['msg'] = '银行列表为空';
            return $back;
        }
       $back['data'] = $bank_list;
        return $back;
    }

    /**
     * @param Request $request
     * @return array
     * 根据省、市、总行获取市下支行
     */
   public function bankBranchInfo(Request $request){
       $back = ['code'=>666,'msg'=>'ok','data'=>[]];
       $yeepay = Config::get('yeepay');
       $request =  $request->post();
       $rules = [
           'headBankCode'  => 'require',
           'provinceCode'   =>'require',
           'cityCode'=>'require',
       ];
       $rule = $this->validate($request,$rules);
       if($rule !== true){
           $back['code'] = -1;
           $back['msg'] = $rule;
           return $back;
       }
        $req = new YopRequest($yeepay['appKey'],$yeepay['private_key'],$yeepay['head_url'],$yeepay['yop_public_key']); 
        $req->addParam("headBankCode", $request['headBankCode']);
        $req->addParam("provinceCode", $request['provinceCode']);
        $req->addParam("cityCode", $request['cityCode']);
     
        $response = YopClient3::post("/rest/v1.0/sys/merchant/bankbranchinfo", $req);

       //取得返回结果
       $response = Helptype::object_array($response);
           if( $response['result'] == NULL)
       {
           $back['code'] = -1;
           $back['msg'] = $response['error'];
           return $back;
       }
       if(!array_key_exists('branchBankInfo', $response['result'])){
            return $back;
       }else{
            $back['data'] = $response['result']['branchBankInfo'];
            return $back;
       }
       
   }

//提现
    public function withdraw_money(Request $request)
    {
        $back = ['code'=>666,'msg'=>'ok','data'=>[]];
        //判断用户是否为商家
        $is_balance = Helptype::is_business($this->user_id);
        if(!$is_balance){
            $back['code'] = -1;
            $back['msg'] = "当前用户不是商家";
            return $back;
        }
        //获取账户余额
        $overage = Helptype::get_balance($this->user_id,0);
        //Helptype::insert_log($back);
        $postData = $request->post();
        //验证传过来的参数
        $rules = [
            'name'  => 'require',
            'money'   => 'number|require',
        ];
        $rule = $this->validate($postData,$rules);
        if($rule !== true){
            $back['code'] = -1;
            $back['msg'] = $rule;
            return $back;
        }
        //判断账户余额
        if($postData['money']>$overage){
            $back['code'] = -1;
            $back['msg'] = '您提取的资金高于您的账户余额';
            return $back;
        }
        //判断身份证是否正确

        //生成订单
        $orderId = date('YmdHis').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        //手续费




        $data = [
            'user_id' =>$this->user_id ,//用户id
            'before_balance' => $overage, //操作前余额
            'money'   => $postData['money'],//当前操作余额
            'after_balance' => $overage + $postData['money'],//操作后余额
            'types' => 0,
            'state' => 0,
            'createtime' => date('Y-m-d H:i:s',time()),
            'batchcode'  => $orderId,
            'out_trade_no'=>'66666',
            'description' => '45556',
            'remark' => '45678900'
        ];
        $operation_log_data = [
            'user_id'=>$this->user_id,
            'module' => 'users',
            'module_id' =>$this->user_id,
            'operation_type' =>1,
            'operation_content' => json_encode(['users' => $data])
        ];
        InsertLog::insert("consume",$data);
        OperationLog::insert($operation_log_data);
        return $back;
    }
}
